package appfight.scene.manager;

import java.util.ArrayList;
import java.util.List;

import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.entity.Entity;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.ITouchArea;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.opengl.buffer.BufferObjectManager;

public class SceneManager {
	
	private Scene _scene;
	
	private List<Entity> _attachList;
	private List<ITouchArea> _touchRegionList;
	private List<IUpdateHandler> _updateHandler;	
	
	
	public SceneManager(Scene s)
	{
		_scene = s;
		Init();
	}
	
	public void attach(Entity s)
	{
		_attachList.add(s);
		_scene.attachChild(s);
	}
	
	public void detach(Entity s)
	{
		_attachList.remove(s);
		_scene.detachChild(s);
	}
	
	public void registerTouchArea(ITouchArea a)
	{
		_touchRegionList.add(a);
		_scene.registerTouchArea(a);
	}
	
	public void unregisterTouchArea(ITouchArea a)
	{
		_touchRegionList.remove(a);
		_scene.unregisterTouchArea(a);
	}
	
	public void registerUpdateHandler(IUpdateHandler h)
	{
		_updateHandler.add(h);
		_scene.registerUpdateHandler(h);
	}
	
	public void unregisterUpdateHandler(IUpdateHandler h)
	{
		_updateHandler.remove(h);
		_scene.unregisterUpdateHandler(h);
	}
	
	public void UnLoadAll()
	{		
		for(Entity s : _attachList)
		{
			if(s instanceof Sprite)	
			{
			BufferObjectManager.getActiveInstance().unloadBufferObject(((Sprite)s).getVertexBuffer());
			}
			_scene.detachChild(s);
		}
		
		for(ITouchArea a : _touchRegionList)
		{
		_scene.unregisterTouchArea(a);
		}
		
		for(IUpdateHandler h : _updateHandler)
		{
		_scene.unregisterUpdateHandler(h);
		}
		
		Init();
	}

	private void Init() 
	{
		_attachList = new ArrayList<Entity>();
		_touchRegionList = new ArrayList<ITouchArea>();
		_updateHandler = new ArrayList<IUpdateHandler>();
	}
}
